iT邦幫忙

2022 iThome 鐵人賽

DAY 26
0
Software Development

SQL rookie 之天天魯一下系列 第 26

Day 26 - SQL Aggregate function 練習

  • 分享至 

  • xImage
  •  

Hello,大家好~~

我們今天要延續昨天練習的aggregate function 並繼續完成情境3、4


經過一天的沉澱後,好像有試出解法了,雖然都好醜 XD

情境3:所有user completed 的todos 平均完成率

SELECT ROUND(COUNT(CASE WHEN completed = true then 1 END)::NUMERIC / COUNT(completed), 2) AS completed_rate
FROM todos

https://ithelp.ithome.com.tw/upload/images/20221010/20150959n8QKOFhS6h.png

如此就能順利解出情境3 了

情境4:各個user 各自completed 的todos 完成率

SELECT "userId", ROUND(COUNT(CASE WHEN completed = true then 1 END)::NUMERIC / COUNT(completed), 2) AS completed_rate
FROM todos
GROUP BY "userId"

https://ithelp.ithome.com.tw/upload/images/20221010/20150959SnkSLwYsHZ.png

接著讓我們試著用subquery 寫出情境4:

SELECT "userId", completed_rate
FROM (
		SELECT "userId", ROUND((COUNT(CASE WHEN completed = true THEN 1 END)::NUMERIC / COUNT(completed)), 2) AS completed_rate
		FROM todos 
		GROUP BY "userId") as completed_sql

那我們又有沒有辦法用Active Record 的方法寫出同樣結果而不用raw_sql 呢?

情境3:所有user completed 的todos 平均率

irb(main):014:0> ((Todo.where(completed: true).count) / (Todo.count).to_f).round(2)
   (0.8ms)  SELECT COUNT(*) FROM "todos" WHERE "todos"."completed" = $1  [["completed", true]]
   (0.6ms)  SELECT COUNT(*) FROM "todos"
0.45

情境4:各個user 各自completed 的todos 完成率

Todo.pluck(:userId).uniq.sort.map do |userid|
  p "#{userid}: #{(Todo.where(userId: userid, completed: true).count / Todo.where(userId: userid).count.to_f).round(2)}"
end

1: 0.52
2: 0.4
3: 0.35
4: 0.3
5: 0.6
6: 0.3
7: 0.45
8: 0.55
9: 0.4
10: 0.6

# 好醜 -_-

啊,那麼今天就先這樣吧!謝謝大家~~


上一篇
Day 25 - SQL Aggregate function(1)
下一篇
Day 27 - SQL: CTE
系列文
SQL rookie 之天天魯一下30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言